package com.bj.disc.ui.login.fragment

import android.Manifest
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableString
import android.text.style.StyleSpan
import android.view.View
import android.widget.RadioButton
import com.ai3d.rfid.R
import com.bj.disc.base.App
import com.ai3d.rfid.base.fragment.BaseVmVdbFragment
import com.ai3d.rfid.common.proxy.ToastProxy
import com.ai3d.rfid.common.utils.HandlerUtils
import com.ai3d.rfid.databinding.FragmentLoginBinding
import com.ai3d.rfid.databinding.ItemPwdBinding
import com.bj.disc.base.InitLanguage
import com.bj.disc.bean.PwdResponse
import com.bj.disc.dialog.RequestPermissionsDialog
import com.bj.disc.ui.login.activity.PwdSetActivity
import com.bj.disc.ui.login.vm.LoginViewModel
import com.bj.disc.util.GridSpaceItemDecoration
import com.blankj.utilcode.util.ConvertUtils
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.permissionx.guolindev.PermissionX


/**
 * @ProjectName : Kolb
 * @Author : weijinsong
 * @Time : 2023/1/4 16:53
 * @Description : 登录
 *
 * TODO   初次设置密码UI
 * 主页TabUI 设置页面UI
 * 报告UI
 * 登录接口可以测试一下
 * 密码图片接口
 *
 */
class LoginFragment : BaseVmVdbFragment<LoginViewModel, FragmentLoginBinding>() {
    private val TAG = "LoginFragment"
    val action: Action by lazy { Action() }

    var list = ArrayList<PwdResponse>()
    var result = arrayOf(-1,-1,-1)
    var resultList = ArrayList<PwdResponse>()
    val resultAdapter:ItemAdapter by lazy { ItemAdapter() }
    val adapter:ItemAdapter by lazy { ItemAdapter() }
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        mDatabind.action = action
        setRadioButtonBold(mDatabind.rbPwd)
        mDatabind.rgPwd.setOnCheckedChangeListener { radioGroup, i ->
            when (i) {
                R.id.rb_pwd -> {
                    mDatabind.viewAssist.visibility = View.INVISIBLE
                    mDatabind.viewPwd.visibility = View.VISIBLE
                    setRadioButtonBold(mDatabind.rbPwd)
                    setRadioButtonNormalStyle(mDatabind.rbAssist)
                    mDatabind.llPwd.visibility = View.VISIBLE
                    mDatabind.viewAssistPanel.visibility = View.GONE
                    mDatabind.rvSelectPwd.visibility=View.VISIBLE
                    mDatabind.llAssist.visibility=View.GONE
                }

                R.id.rb_assist -> {
                    mDatabind.viewPwd.visibility = View.INVISIBLE
                    mDatabind.viewAssist.visibility = View.VISIBLE
                    setRadioButtonBold(mDatabind.rbAssist)
                    setRadioButtonNormalStyle(mDatabind.rbPwd)
                    mDatabind.llPwd.visibility = View.GONE
                    mDatabind.viewAssistPanel.visibility = View.VISIBLE
                    mDatabind.rvSelectPwd.visibility=View.GONE
                    mDatabind.llAssist.visibility=View.VISIBLE
                }
            }
        }
//        mDatabind.tabLoginType.addTab(
//            mDatabind.tabLoginType.newTab().setText("密码选择")
//        );
//        mDatabind.tabLoginType.addTab(
//            mDatabind.tabLoginType.newTab().setText("辅助验证")
//        );
//
//        mDatabind.tabLoginType.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
//            override fun onTabSelected(tab: TabLayout.Tab?) {
//
//
//            }
//
//            override fun onTabUnselected(tab: TabLayout.Tab?) {
//            }
//
//            override fun onTabReselected(tab: TabLayout.Tab?) {
//            }
//
//        })
    }

    private fun setRadioButtonNormalStyle(radioButton: RadioButton) {
        val text = radioButton.text.toString()
        val spannableString = SpannableString(text)
        spannableString.setSpan(StyleSpan(Typeface.NORMAL), 0, text.length, 0)
        radioButton.text = spannableString
    }

    private fun setRadioButtonBold(radioButton: RadioButton) {
        val text = radioButton.text.toString()
        val spannableString = SpannableString(text)
        spannableString.setSpan(StyleSpan(Typeface.BOLD), 0, text.length, 0)
        radioButton.text = spannableString
    }

    override fun initData() {
        super.initData()
//        mDatabind.etLogin.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
//        mDatabind.etLogin.transformationMethod = PasswordTransformationMethod.getInstance()
        //   requestPermission()
        for (i in 0..15){
            list.add(PwdResponse("https://lanhuapp.com/be6ff181-c5de-443e-82cd-933505b34910"))
        }

        adapter.setNewInstance(list)
        mDatabind.rvSelectPwd.adapter=adapter

        mDatabind.rvResult.adapter=resultAdapter
        mDatabind.rvResult.addItemDecoration(
            GridSpaceItemDecoration(
                3,
                0, ConvertUtils.dp2px(32f)
            )
        )
        resultAdapter.setNewInstance(resultList)
    }

    inner class ItemAdapter : LoadMoreModule,
        BaseQuickAdapter<PwdResponse, BaseDataBindingHolder<ItemPwdBinding>>(
            R.layout.item_pwd
        ) {

        private var action = Action()
        override fun convert(
            holder: BaseDataBindingHolder<ItemPwdBinding>,
            item: PwdResponse
        ) {
            item.realPosition=holder.adapterPosition
            holder.dataBinding?.item = item
            holder.dataBinding?.action = action
            holder.dataBinding?.executePendingBindings()
            holder.dataBinding?.ivIcon?.let {
                Glide.with(requireActivity()).load(item.url).into(it)
            }


        }


        inner class Action {

            fun select(item: PwdResponse) {
                if (item.isSelected) {
                    // 取消选择
                    item.isSelected = false
                     result.forEachIndexed { index, it ->
                         if(it==item.realPosition){
                             result[index]=-1
                         }
                     }
                    resultList.clear()
                    result.forEach {
                        if(it!=-1) {
                            resultList.add(list.get(it))
                        }
                    }
                } else {
                    // 如果已经选择了3个，则不能再选择
                    var allSelect = true
                    result.forEach {
                        if(it==-1){
                            allSelect=false
                        }
                    }
                    if (!allSelect) {
                        item.isSelected=true
                       run out@{
                           result.forEachIndexed { index, it ->
                               if(it==-1){
                                   result[index]=item.realPosition
                                   item.selectedPosition=index
                                   return@out
                               }
                           }
                       }
                        resultList.clear()
                        result.forEach {
                            if(it!=-1) {
                                resultList.add(list.get(it))
                            }
                        }
                    }
                }
                resultAdapter.setNewInstance(resultList.sortedBy { it.selectedPosition }.toMutableList())
                notifyDataSetChanged()
            }


        }


    }

    private fun requestPermission() {
        val hasRecordAudioPermission =
            PermissionX.isGranted(App.instance, Manifest.permission.RECORD_AUDIO)
        if (hasRecordAudioPermission) {
        } else {
            RequestPermissionsDialog(
                RequestPermissionsDialog.RECORD_AUDIO_PERMISSIONS,
                requireActivity()
            ) {
                if (it) {
                    PermissionX.init(requireActivity())
                        .permissions(
                            Manifest.permission.RECORD_AUDIO,
                        )
                        .onExplainRequestReason { deniedList ->
                        }
                        .request { allGranted, grantedList, deniedList ->
                            if (allGranted) {
                            } else {
                                ToastProxy.showShort(R.string.permission_record_audio_request)
                            }
                        }
                } else {
                    ToastProxy.showShort(R.string.permission_record_audio_request)
                }

            }.show()
        }
    }

    override fun createObserver() {

    }

    override fun onResume() {
        super.onResume()

    }

    override fun onPause() {
        super.onPause()

    }


    override fun onDestroy() {
        super.onDestroy()
        HandlerUtils.removeCallbacksAndMessages()
    }


    inner class Action {
        fun logout() {
//            activity?.finish()
            InitLanguage.finishAll()
        }

        fun copy() {
            val clipboardManager =
                context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            // 创建ClipData对象
            val clipData = ClipData.newPlainText("label", "cccc")
            // 将ClipData对象放入剪贴板
            clipboardManager.setPrimaryClip(clipData)
            // 提示用户已成功复制
            ToastProxy.showShort("已复制到剪贴板")
        }

        fun clear() {
            result.forEachIndexed { index, it ->
                result[index]=-1
            }
            resultList.clear()
            list.forEach {
                it.isSelected=false
            }
            adapter.setNewInstance(list)
            adapter.notifyDataSetChanged()
            resultAdapter.setNewInstance(resultList)

        }

        fun login() {
            PwdSetActivity.startPwdSetActivity(requireActivity())
        }

        fun clearName() {
            mDatabind.etName.text.clear()
        }


        fun gotoForgetPwd() {
            hideSoftKeyboard(activity)
            clear()
//            ForgetPwdActivity.startForgetActivity(
//                requireActivity(),
//                mDatabind.edtAccount.text.toString()
//            )
        }

        fun register() {
        }
    }
}